package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.mapper.SafeMapper;
import com.smart.village.big.screen.service.SafeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.List;

@Service
public class SafeServiceImpl implements SafeService {
    @Autowired
    private SafeMapper safeMapper;

    @Override
    public JSONObject getPatrolTaskPlan(String type, String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> shopList = safeMapper.getPatrolTaskPlan(type, townNumber, villageNumber);;
        PageInfo<JSONObject> pageInfo = new PageInfo<>(shopList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getExceptionTip(String source, String townNumber, String villageNumber) {
        return safeMapper.getExceptionTip(source, townNumber, villageNumber);
    }

    @Override
    public JSONObject getPatrolManager(String townNumber, String villageNumber) {
        List<JSONObject> patrolManager = safeMapper.getPatrolManager(townNumber, villageNumber);
        int total = 0;
        int checkIn = 0;
        int notCheckIn = 0;

        for (int i = 0; i < patrolManager.size(); i++) {
            JSONObject jsonObject = patrolManager.get(i);
            if (jsonObject.getInteger("flag") == 0) {
                notCheckIn += jsonObject.getInteger("cnt");
            }
            if (jsonObject.getInteger("flag") == 1) {
                checkIn += jsonObject.getInteger("cnt");
            }

        }
        total += checkIn + notCheckIn;
        // 计算 checkIn  / total  的百分比，保留两位小数
        BigDecimal checkInPercent;
        if (total == 0) {
            checkInPercent = new BigDecimal("0");
        } else {
            checkInPercent = new BigDecimal(checkIn).divide(new BigDecimal(total), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", total);
        jsonObject.put("checkIn", checkIn);
        jsonObject.put("notCheckIn", notCheckIn);
        jsonObject.put("checkInPercent", checkInPercent);
        return jsonObject;
    }

    @Override
    public JSONObject getSafeCoordsList(String townNumber, String villageNumber) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "FeatureCollection");
        JSONObject crs = new JSONObject();
        crs.put("type", "name");
        JSONObject crsP = new JSONObject();
        crsP.put("name", "EPSG:4490");
        crs.put("properties", crsP);

        jsonObject.put("crs", crs);
        List<JSONObject> list = safeMapper.getSafeCoordsList(townNumber, villageNumber);
        List<JSONObject> features = Lists.newArrayList();
        for (JSONObject coords : list) {
            JSONObject feature = new JSONObject();
            feature.put("type", "Feature");
            feature.put("id", coords.getString("Shop_SerialNumber"));
            JSONObject geometry = new JSONObject();
            geometry.put("type", "point");
            geometry.put("coordinates", coords.getString("Coord").replace(" ", ""));
            feature.put("geometry", geometry);
            feature.put("properties", coords);
            if (!ObjectUtils.isEmpty(coords.getString("Coord")) && !coords.getString("Coord").replace(" ", "").equals("[]]")) {
                coords.remove("Coords");
                coords.remove("Coord");
                features.add(feature);
            }
        }
        jsonObject.put("features", features);
        return jsonObject;
    }

    @Override
    public List<JSONObject> getSafeTagsList() {
        return safeMapper.getSafeTagsList();
    }

    @Override
    public JSONObject getMonitorDeviceList(String townNumber, String villageNumber, String usageTypeSerialNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> deviceList = safeMapper.getDeviceCoords("ME0000000000001", usageTypeSerialNumber, townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(deviceList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getMonitorDeviceUsageTypeList() {
        return safeMapper.getMonitorDeviceUsageTypeList();
    }

    @Override
    public JSONObject getSafeAssess(String townNumber, String villageNumber) {
        List<JSONObject> safeAssessCurrentYear = safeMapper.getSafeAssess(townNumber, villageNumber, 0);
        List<JSONObject> safeAssessLastYear = safeMapper.getSafeAssess(townNumber, villageNumber, 1);
        // 组成 这样结构的 xAxis 中的data 是循环 safeAssessCurrentYear 中的 category_name

        List<String> xAxisData = Lists.newArrayList();
        for (JSONObject jsonObject : safeAssessCurrentYear) {
            xAxisData.add(jsonObject.getString("category_name"));
        }

        // 组成 这样结构的 series 中的数据 是 从safeAssessCurrentYear，safeAssessLastYear 中依次 遍历 第一个，第二个，第三个，第四个
        List<Integer> seriesDataCurrentYear = Lists.newArrayList();
        List<Integer> seriesDataLastYear = Lists.newArrayList();
        for (int i = 0; i < safeAssessCurrentYear.size(); i++) {
            seriesDataCurrentYear.add(safeAssessCurrentYear.get(i).getInteger("cnt"));
            seriesDataLastYear.add(safeAssessLastYear.get(i).getInteger("cnt"));
        }

        List jsonList = Lists.newArrayList();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", seriesDataLastYear);
            jsonObject.put("name", "第一年");
            jsonList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put("data", seriesDataCurrentYear);
            jsonObject.put("name", "第二年");
            jsonList.add(jsonObject);
        JSONObject result = new JSONObject();
        result.put("axis", xAxisData);
        result.put("list", jsonList);

        //
        // xAxis: {
        //    type: 'category',
        //    data: ['基层防火', '溺水事件', '极端天气', '边境治安'],
        //    axisLabel : {
        //      color: '#ffffff'
        //    }
        //  },
        //  series: [
        //    {
        //      name: '第一年',
        //      type: 'bar',
        //      barGap:0,
        //      barWidth:'25%',
        //      data: [120, 140, 230, 100]
        //    },
        //    {
        //      name: '第二年',
        //      type: 'bar',
        //       barWidth:'25%',
        //      data: [150, 100, 200, 140]
        //    }
        //  ]
        return result;
    }

    @Override
    public JSONObject getSafeIndex(String townNumber, String villageNumber) {
        List<JSONObject> safeIndex = safeMapper.getSafeIndex(townNumber, villageNumber );
        List<String> xAxisData = Lists.newArrayList();
        List<Double> Water_Level = Lists.newArrayList();
        List<Double> Flow_Speed = Lists.newArrayList();

        for (JSONObject jsonObject : safeIndex) {
            xAxisData.add(jsonObject.getString("MONTH")+"月");
            Water_Level.add(jsonObject.getDouble("Water_Level"));
            Flow_Speed.add(jsonObject.getDouble("Flow_Speed"));
        }
        List jsonList = Lists.newArrayList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", Water_Level);
        jsonObject.put("name", "水位(米)");
        jsonList.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("data", Flow_Speed);
        jsonObject.put("name", "流速(米/秒)");
        jsonList.add(jsonObject);

        JSONObject result = new JSONObject();
        result.put("axis", xAxisData);
        result.put("list", jsonList);
        return result;
    }

    @Override
    public JSONObject getPatrolTaskPlanCoords(String taskSerialNumber, String taskPlanSerialNumber) {
        JSONObject jsonObject = new JSONObject();
        JSONObject patrolTaskPlan = safeMapper.getPatrolTaskPlanByTaskSerialNumber(taskSerialNumber);
        if (ObjectUtils.isEmpty(patrolTaskPlan)){
            return jsonObject;
        }

        List<String> planCoords = Lists.newArrayList();
        planCoords.add(patrolTaskPlan.getString("Coord"));
        List<JSONObject> actualCoords = Lists.newArrayList();
        jsonObject.put("planCoords", planCoords);
        List<JSONObject> actualCoordsList = safeMapper.getPatrolResultCoordsByTaskPlanSerialNumber(taskPlanSerialNumber);
        for (JSONObject jsonObject1 : actualCoordsList) {
            JSONObject actualCoord = new JSONObject();
            actualCoord.put("Coord", jsonObject1.getString("Coord"));
            actualCoord.put("PersonName", jsonObject1.getString("Personal_Name"));
            actualCoords.add(actualCoord);
        }
        jsonObject.put("actualCoords",actualCoords);
        return jsonObject;
    }
}
